package gameCode.ui;

import gameCode.domain.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;


public class RegisterForm extends JFrame implements ActionListener {
    private JTextField usernameField;
    private JPasswordField passwordField1;
    private JPasswordField passwordField2;
    private JButton registerButton;

    public RegisterForm() {
        //初始化界面
        intJFrame();
        //在这个界面中添加内容
        intView();
        //让当前界面显示出来
        this.setVisible(true);
    }

    private void intJFrame() {
        // 创建容器
        Container container = getContentPane();
        container.setLayout(new FlowLayout());

        //1.创建用户名
        Font usernameFont = new Font(null, Font.BOLD, 16);
        Component username = container.add(new JLabel("用户名"));
        username.setForeground(Color.white);
        username.setBounds(160, 48, 55, 22);
        username.setFont(usernameFont);

        //2.添加用户名输入框
        usernameField = new JTextField(20);
        usernameField.setBounds(223, 46, 200, 30);
        container.add(usernameField);


        //1.创建密码文字
        Font passwordFont1 = new Font(null, Font.BOLD, 16);
        Component password1 = container.add(new JLabel("密码"));
        password1.setBounds(210, 90, 40, 22);
        password1.setForeground(Color.white);
        //设置文字大小
        password1.setFont(passwordFont1);

        //2.创建密码输入框
        passwordField1 = new JPasswordField(20);
        passwordField1.setBounds(263, 87, 160, 30);
        container.add(passwordField1);


        //确认密码文字
        Font passwordFont2 = new Font(null, Font.BOLD, 15);
        Component password2 = container.add(new JLabel("确认密码"));
        password2.setBounds(190, 130, 65, 22);
        password2.setForeground(Color.white);
        //设置文字大小
        password2.setFont(passwordFont2);

        //2.创建密码输入框
        passwordField2 = new JPasswordField(20);
        passwordField2.setBounds(263, 127, 160, 30);
        container.add(passwordField2);


        // 创建注册按钮
        registerButton = new JButton();
        registerButton.setIcon(new ImageIcon("doudizhu\\image\\login\\注册按钮.png"));
        registerButton.addActionListener(this);
        registerButton.setBounds(320, 310, 128, 47);
        //去除按钮的边框
        registerButton.setBorderPainted(false);
        //去除按钮的背景
        registerButton.setContentAreaFilled(false);
        container.add(registerButton);

        // 创建返回按钮
        JButton backspace = new JButton();
        backspace.setIcon(new ImageIcon("doudizhu\\image\\login\\返回按钮.png"));
        backspace.addActionListener(this);
        backspace.setBounds(180, 305, 135, 47);
        //去除按钮的边框
        backspace.setBorderPainted(false);
        //去除按钮的背景
        backspace.setContentAreaFilled(false);
        container.add(backspace);
        //7.添加背景图片
        JLabel background = new JLabel(new ImageIcon("doudizhu\\image\\login\\background.png"));
        background.setBounds(0, 0, 633, 423);
        this.getContentPane().add(background);

    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        RegisterForm that = (RegisterForm) o;
        return Objects.equals(usernameField, that.usernameField) && Objects.equals(passwordField1, that.passwordField1) && Objects.equals(passwordField2, that.passwordField2) && Objects.equals(registerButton, that.registerButton);
    }

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource().equals(registerButton)) {
            // 获取输入的用户名和密码
            String username = usernameField.getText();
            String password = new String(passwordField1.getPassword());
            String rePassword = new String(passwordField2.getPassword());
            //注册按钮事件 校验用户名和密码
            //1.用户名，密码不能为空
            if (username.isEmpty() || password.isEmpty() || rePassword.isEmpty()) {
                //错误
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            } else {
                //2.判断两次密码输入是否一致
                if (!(password.equals(rePassword))) {
                    //确认密码逻辑、重写了equals比较值还是比较不了
                    JOptionPane.showMessageDialog(this, "两次密码不一致！", "错误", JOptionPane.INFORMATION_MESSAGE);
                } //3.判断用户名和密码的格式是否正确
                else if (!username.matches("[a-zA-Z0-9]{4,16}")) {
                    usernameField.setText("");
                    JOptionPane.showMessageDialog(this, "用户名不符合规则！", "错误", JOptionPane.ERROR_MESSAGE);
                } else if (!password.matches("\\S*(?=\\S{6,})(?=\\S*\\d)(?=\\S*[a-z])\\S*")) {
                    usernameField.setText("");
                    JOptionPane.showMessageDialog(this, "密码不符合规则，至少包含1个小写字母，1个数字，长度至少6位！", "错误", JOptionPane.ERROR_MESSAGE);

                } //4.判断用户名是否已经重复
                else if (containsUsername(username)) {
                    usernameField.setText("");
                    JOptionPane.showMessageDialog(this, "用户名已经存在，请重新输入！", "错误", JOptionPane.ERROR_MESSAGE);
                } else {
                    //注册成功 清空输入框
                    usernameField.setText("");
                    passwordField1.setText("");
                    passwordField2.setText("");
                    // 注册成功提示框
                    JOptionPane.showMessageDialog(this, "注册成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    //IO写入账号密码
                    try {
                        IOFileWriter(username, password);
                        LoginJFrame.allUsers.add(new User(username, password));
                        System.out.println(new User(username, password));

                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                //校验错误 清空密码
                passwordField1.setText("");
                passwordField2.setText("");
            }
        } else {
            //关闭当前登录界面
            this.setVisible(false);
            //注册成功时，添加完新账号，没有刷新缓冲池
            //直接把新账号密码 存入的集合allUser
            //(重启程序)
            new LoginJFrame();
//            System.exit(0);
        }

    }

    private void IOFileWriter(String username, String password) throws IOException {
        //把注册成功的账户、密码（续写）写入文件
        //每行 写入格式：  username=zhangsan&password=123

        BufferedWriter fw = new BufferedWriter(new FileWriter("doudizhu\\userInfo.txt", true));
        File f = new File("doudizhu\\userInfo.txt");
        if (f.length() == 0) {
            //是空文件 不换行
            fw.write("username="+ username + "&password=" + password);
        } else {
            fw.newLine();
            fw.write("username="+ username + "&password=" + password);
        }
        //写完就存入 关流
        fw.flush();
        fw.close();
    }

    public boolean containsUsername(String username) {
        for (User u : LoginJFrame.allUsers) {
            if (u.getUsername().equals(username)) {
                return true;
            }
        }
        return false;
    }

    private void intView() {
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置关闭模式
        this.setTitle("注册界面"); // 设置窗口标题
        setIconImage(Toolkit.getDefaultToolkit().getImage("doudizhu\\image\\dizhu.png"));  //设置图标
        this.setSize(633, 423);// 设置窗口大小和可见性
        this.setResizable(false);//设置窗口无法进行调节
        this.setLocationRelativeTo(null);//居中
        this.setAlwaysOnTop(true);//置顶
        this.setLayout(null);//取消内部默认布局
    }
}


